package com.sf.su.marathon.manager.impl;

import com.sf.su.marathon.dao.domain.Group;
import com.sf.su.marathon.dao.domain.JoinGroupList;
import com.sf.su.marathon.dao.domain.User;
import com.sf.su.marathon.dao.dto.GroupDetailInfo;
import com.sf.su.marathon.dao.mapper.GroupMapper;
import com.sf.su.marathon.dao.mapper.JoinGroupListMapper;
import com.sf.su.marathon.dao.mapper.UserMapper;
import com.sf.su.marathon.manager.GroupManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by shawn on 2017/12/15.
 */
@Component
public class GroupManagerImpl implements GroupManager {

   @Autowired
   private GroupMapper groupMapper;

   @Autowired
   private UserMapper userMapper;

   @Autowired
   private JoinGroupListMapper joinGroupListMapper;

    @Override
    public Group selectGroupById(String groupId) {
        return groupMapper.selectByPrimaryKey(groupId);
    }

    @Override
    public int insert(Group group) {
        return groupMapper.insertSelective(group);
    }

    @Override
    public int updateGroup(Group record) {
        return groupMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public boolean signup(String openId, Group group) {
        JoinGroupList joinGroupList = new JoinGroupList();
        if(groupMapper.updateByPrimaryKeySelective(group)>0){
            User user = userMapper.selectByOpenId(openId);
            if (user != null) {
                joinGroupList.setUserId(user.getId());
                joinGroupList.setGroupId(group.getId());
                if(joinGroupListMapper.insertSelective(joinGroupList)>0){
                    return true;
                }
            }else{
                return false;
            }
        }
        return false;
    }

    @Override
    public List<Group> selectNotFullAndExpire() {
        return groupMapper.selectNotFullAndExpire();
    }

    @Override
    public List<Group> getByMarketId(String mktId) {
        return groupMapper.getByMarketId(mktId);
    }

    @Override
    public List<User> getUserInGroup(String groupId) {
        return joinGroupListMapper.getUserInGroup(groupId);
    }

    @Override
    public List<GroupDetailInfo> getGroupList() {


        List<GroupDetailInfo> groupList = groupMapper.getGroupList();

        if(null == groupList){
            new ArrayList<>();
        }

        return groupList;
    }
}
